<template>
    <div class="opening">

    </div>
    <el-divider border-style="dashed" style="background-color: #f5f5f5;"><p style="background-color: #f5f5f5;">已成功连接客服，你们可以开始聊天了</p></el-divider>
    
    <div v-for="(line ,index) in conver"  :key="index" style="width: 100%;">
        <div v-if="line.whosspeaking =='0'" class="bubble" style="margin-left: 52%; color: white; padding-left: 5px; padding-right: 5px; float: right; background-color:chartreuse;" v-html="line.content">
        </div>
        <div v-else class="bubble" style="margin-right: 52%; padding-left: 5px; padding-right: 5px;border-style: solid;  border-color: black; border-width: 1px; float:left; background-color: white;" v-html="line.content">
        </div> 
    </div>
 
    <div class="stable">
            <el-input
              v-model="textarea2"
              maxlength="100"
              show-word-limit
              placeholder="Input your question here or upload the image"
              :rows="3"
              type="textarea"        
            />
            <el-button-group style="float: right; margin-top: 5px">
              <el-button type="primary" :icon="PictureFilled" @click="uploadRef.$el.querySelector('input').click()"/>
              <el-button
                type="primary"
                :icon="Promotion" @click="sendMsg"
                >发送</el-button
                >
            
              
            </el-button-group>
            <el-button
                type="danger"
                 @click="leave"
                >离开</el-button
                >
            <el-upload
                ref="uploadRef"
                class="avatar-uploader"
                :show-file-list="false"
                action="/api/upload"
                name="file"
                :headers="{'Authorization': tokenStore.token}"
                :on-success="uploadSuccess"
            >
              <el-image v-if="imgUrl" :src="imgUrl" class="pic" :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="srcList"
                :initial-index="4"
                fit="cover"
                style="width: auto; height: 100px"/>
            </el-upload>
            
        </div>
</template>
<script lang="ts" setup>
import { PictureRounded,Service, Star, Plus, Select,Promotion, PictureFilled,
  CirclePlus
}from '@element-plus/icons-vue'
import useUserInfoStore from "@/stores/userInfo.js";
const userInfoStore = useUserInfoStore();
const avasrc = ref(userInfoStore.userInfo.avatar)
const imgUrl= ref('')
const textarea2 = ref('')
import { ref, onMounted } from "vue";
const uploadSuccess=(result)=>{


    imgUrl.value=result.data;
    let imgHtml = '<img src="'+ imgUrl.value+
                    '" class="pic" :zoom-rate="1.2" \
                    :max-scale="7" \
                    :min-scale="0.2" \
                    :preview-src-list="srcList" \
                    fit="cover" style="width: auto; height: 100px"/>'
    let line2 ={
        username: userInfoStore.userInfo.realname,
        content: imgHtml,
        whosspeaking: '0',
        time: (new Date()).toLocaleString('ja')
    }
    srcList.value.push(imgUrl.value)
    conver.value.push(line2)
    ws.send(JSON.stringify(line2))
    imgUrl.value = ''
}
const uploadRef = ref()
const srcList = ref([])
import{useTokenStore} from "@/stores/token.js";
import router from '@/router';
const  tokenStore = useTokenStore();

const conver =ref([])

const sendMsg =()=>{
    if(textarea2.value=='')
        return
    let line1 ={
        username: userInfoStore.userInfo.realname,
        content:  textarea2.value,
        whosspeaking: '0',
        time: (new Date()).toLocaleString('ja')
    }
    conver.value.push(line1)

    ws.send(JSON.stringify(line1))
    textarea2.value=''
}

const leave =()=>{
  ws.close()
  emit('senddata2',props.inf);
  router.push({path:'/cservice',query:{p:1}})  //待改
}

const emit = defineEmits(['senddata','senddata2']);
const props =  defineProps<{inf : string; }>();

var ws;

onMounted(()=>{
  
  if (typeof (WebSocket) == "undefined") {
      console.log("遗憾：您的浏览器不支持WebSocket");
  } else {
      console.log("恭喜：您的浏览器支持WebSocket");
  }
  //ws=new WebSocket('ws://localhost:5173/api/ws?userId='+userInfoStore.userInfo.phonenumber+'&mysessionid='+router.currentRoute.value.query);

  ws = new WebSocket('ws://localhost:5173/ws/'+String(userInfoStore.userInfo.phonenumber)+'/'+router.currentRoute.value.query.sessionid)
const flag = ref(1)
ws.onmessage = (evt) =>{
    
    let _data = evt.data;
    let line = JSON.parse(_data)
    line.whosspeaking = '1'
    let name = line.username;
    console.log(name+'-'+props.inf)
    if(flag.value==1){
      emit('senddata',name,props.inf);
      flag.value=0;
    }
    
    conver.value.push(line)

}

})







/*
   
  let websocket = null;

  onMounted(async () => {
    initTestWebSocket();
  });

  onBeforeMount(async()=>{
    websocket && websocket.close();
  });

  const initTestWebSocket = async () => {
    const userId = '当前用户ID';
    console.log("尝试建立websockect连接");
    websocket = new WebSocket(`/ws/test/${userId}`);
    websocket.onopen = function (event) {
      console.log("建立连接");
    }
    websocket.onclose = function (event) {
      console.log('连接关闭')
      //尝试重连websocket
      reconnectMessageWebSocket();
    }
    //建立通信后，监听到后端的数据传递
    websocket.onmessage = function (event) {
      // 打印后端传来的数据
      console.log(event.data);
      // 调用WebSocket对象的send方法可向后端发送数据
      // websocket.send("test data");
    }
    websocket.onerror = function () {
      console.log("数据发送失败");
    }
    // 窗口关闭前关闭WebSocket连接
    window.onbeforeunload = function () {
      websocket.close();
    }
  };

  // 重连
  const reconnectMessageWebSocket = () => {
    console.log("正在重连");
    // 进行重连
    setTimeout(() => {
      initTestWebSocket();
    }, 1000);
  }
    */

</script>



<style scoped>
.bubble{
    border-radius: 8px;
    min-width: 40px;
    max-width: 80%;
    overflow-wrap: normal;
    margin-top: 20px;
}


</style>